#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化演示：网络拓扑和基础功能展示
================================

本演示展示了项目的基础功能，包括：
1. 创建不同类型的网络拓扑
2. 计算网络统计信息
3. 可视化网络结构

作者：AI Assistant
日期：2024
"""

import numpy as np
import matplotlib.pyplot as plt
import sys
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

def main():
    """主函数：运行简化演示"""
    print("=" * 60)
    print("DUCA项目 - 网络拓扑演示")
    print("=" * 60)
    
    try:
        # 导入必要的模块
        from src.network import Network
        print("✓ 网络模块导入成功")
        
        # 演示不同的网络拓扑
        topologies = [
            ('complete', '完全连接图', {}),
            ('ring', '环形网络', {}),
            ('star', '星形网络', {}),
            ('random', '随机网络', {'connectivity': 0.4}),
            ('grid', '网格网络', {'rows': 3, 'cols': 3})
        ]
        
        print(f"\n将创建 {len(topologies)} 种不同的网络拓扑：")
        print("-" * 40)
        
        for i, (topology, name, kwargs) in enumerate(topologies, 1):
            print(f"\n{i}. {name} ({topology})")
            
            # 创建网络
            if topology == 'grid':
                num_nodes = 9  # 3x3网格
            else:
                num_nodes = 6
                
            network = Network(num_nodes=num_nodes, topology=topology, **kwargs)
            
            # 获取网络统计信息
            stats = network.get_network_statistics()
            
            # 显示统计信息
            print(f"   节点数量: {stats['num_nodes']}")
            print(f"   边数: {stats['num_edges']}")
            print(f"   连通性: {'是' if stats['is_connected'] else '否'}")
            
            if stats['is_connected']:
                print(f"   网络直径: {stats['diameter']}")
                print(f"   平均路径长度: {stats['average_path_length']:.3f}")
                print(f"   聚类系数: {stats['clustering_coefficient']:.3f}")
                print(f"   代数连通度: {stats['algebraic_connectivity']:.3f}")
                print(f"   共识收敛速率: {stats['consensus_rate']:.3f}")
            
        print("\n" + "=" * 60)
        print("网络统计演示完成！")
        
        # 询问是否进行可视化
        try:
            choice = input("\n是否要可视化网络拓扑？(y/n): ").lower().strip()
            if choice in ['y', 'yes', '是', '']:
                visualize_networks(topologies)
        except KeyboardInterrupt:
            print("\n用户取消操作")
            
        print("\n" + "=" * 60)
        print("演示程序结束")
        print("=" * 60)
        
    except ImportError as e:
        print(f"❌ 模块导入失败: {e}")
        print("请确保已安装所有依赖包并激活虚拟环境")
        return False
    except Exception as e:
        print(f"❌ 运行出错: {e}")
        import traceback
        traceback.print_exc()
        return False
    
    return True

def visualize_networks(topologies):
    """可视化不同的网络拓扑"""
    print("\n正在生成网络可视化图...")
    
    try:
        from src.network import Network
        import networkx as nx
        
        fig, axes = plt.subplots(2, 3, figsize=(15, 10))
        axes = axes.flatten()
        
        for i, (topology, name, kwargs) in enumerate(topologies):
            if topology == 'grid':
                num_nodes = 9
            else:
                num_nodes = 6
                
            network = Network(num_nodes=num_nodes, topology=topology, **kwargs)
            
            plt.sca(axes[i])
            
            if topology == 'grid':
                pos = nx.spring_layout(network.graph, iterations=50)
            elif topology == 'star':
                pos = nx.spring_layout(network.graph, center=[0])
            else:
                pos = nx.spring_layout(network.graph)
            
            # 绘制网络
            nx.draw_networkx_nodes(network.graph, pos, 
                                 node_color='lightblue',
                                 node_size=300, alpha=0.9)
            nx.draw_networkx_labels(network.graph, pos, font_size=10)
            nx.draw_networkx_edges(network.graph, pos, alpha=0.5)
            
            plt.title(f"{name}\n({network.graph.number_of_nodes()}节点, "
                     f"{network.graph.number_of_edges()}边)", fontsize=12)
            plt.axis('off')
        
        # 隐藏多余的子图
        if len(topologies) < len(axes):
            axes[-1].axis('off')
            
        plt.tight_layout()
        plt.savefig('network_topologies.png', dpi=300, bbox_inches='tight')
        plt.show()
        
        print("✓ 网络拓扑图已保存为 'network_topologies.png'")
        
    except Exception as e:
        print(f"❌ 可视化失败: {e}")

def demonstrate_matrix_properties():
    """演示网络矩阵属性"""
    print("\n" + "=" * 40)
    print("网络矩阵属性演示")
    print("=" * 40)
    
    from src.network import Network
    
    # 创建一个小型完全连接网络
    network = Network(num_nodes=4, topology='complete')
    
    print("网络矩阵:")
    print(f"邻接矩阵:\n{network.adjacency_matrix}")
    print(f"\n拉普拉斯矩阵:\n{network.laplacian_matrix}")
    print(f"\n权重矩阵:\n{network.weight_matrix}")
    
    # 验证权重矩阵的双随机性质
    row_sums = np.sum(network.weight_matrix, axis=1)
    col_sums = np.sum(network.weight_matrix, axis=0)
    
    print(f"\n权重矩阵行和: {row_sums.flatten()}")
    print(f"权重矩阵列和: {col_sums.flatten()}")
    print(f"是否为双随机矩阵: {np.allclose(row_sums, 1) and np.allclose(col_sums, 1)}")

if __name__ == "__main__":
    success = main()
    
    if success:
        try:
            choice = input("\n是否要查看矩阵属性演示？(y/n): ").lower().strip()
            if choice in ['y', 'yes', '是']:
                demonstrate_matrix_properties()
        except KeyboardInterrupt:
            print("\n程序结束")
    
    if not success:
        sys.exit(1) 